package com.concurrent.blockingq;

import java.util.concurrent.BlockingQueue;

public class BQProducer implements Runnable{

	private Thread thread;
	private String name;
	private BlockingQueue<String> q;
	private long timeToSleep;
	
	public BQProducer(String name, BlockingQueue<String> q, long timeToSleep){
		this.name = name;
		this.q = q;
		this.timeToSleep = timeToSleep;
		
		thread = new Thread(this, name);
	}
	
	public void start(){
		thread.start();
	}
	
	public void run(){
	
		for(int i=0; i<10; i++){
			try {
				System.out.println(name + " trying to add");

				//add method throw exception if no space is available, hence using offer
				if (!q.offer(i + "")) {  
					long start = System.currentTimeMillis();  
				
					//offer method is non blocking that's why using put
					q.put(i + "");
					System.out.println(name + " :It seems Consumer is slow. Producer waited for "  
					+ (System.currentTimeMillis() - start)  
					+ "ms");  
				}  
				System.out.println(name + ": produced : " + i);
				Thread.sleep(timeToSleep);
				
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	}
}
